↜ Back to index Introduction to Numerical Analysis 1
Solution Lecture a7
Exercise 1
! Implementation of Newton's method for exp x + x = 5
! with a stopping condition
implicit none
real x, F, Fprime, d, p, q
integer k
! Enter the starting x0
read *, x
do k = 1, 100
= exp(x) + x - 5
F = exp(x) + 1
Fprime = F / Fprime
d = x - d
x if (abs(d) < 1e-3) then
print *, k, 'iterations needed'
exit
endif
enddo
end
Iterations needed: 5, 8, 12
Exercise 2
! Implementation of Newton's method for x^3 + p x + q = 0
! with a stopping condition
implicit none
real x, F, Fprime, d, p, q
integer k
read *, p, q, x
print *, x
do k = 1, 100
= x**3 + p * x + q
F = 3 * x**2 + p
Fprime if (abs(Fprime) < 1e-6) then
print *, 'Error: the derivative is too close to zero'
stop
endif
= F / Fprime
d = x - d
x ! We stop the iteration if x does not change more than a certain value
if (abs(d) < 1e-3) then
print *, 'x =', x
print *, k, 'iterations needed'
! stop the loop
stop
endif
print *, x
enddo
print *, 'Method does not converge'
end
Exercise 3
! Implementation of Newton's method for x^3 + p x + q = 0
! with a stopping condition
implicit none
real x, F, Fprime, d, p, q
integer k, i, r
read *, r
do i = -r, r
= i
x
= -2.
p = 2.
q
do k = 1, 100
= x**3 + p * x + q
F = 3 * x**2 + p
Fprime if (abs(Fprime) < 1e-6) then
print *, 'Error: the derivative is too close to zero'
stop
endif
= F / Fprime
d = x - d
x ! We stop the iteration if x does not change more than a certain value
if (abs(d) < 1e-3) then
print *, i, k
! stop the loop
exit
endif
enddo
enddo
end